package com.jianguozh.difs.framework.base;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jianguozh.difs.common.bean.IErrorCode;
import com.jianguozh.difs.common.bean.R;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * 基础controller
 *
 * @author hanrs
 * @email 4076130@qq.com
 * @since 2022/3/9 18:30
 */
public class BaseController {

    private static final String ANTD_TABLE_PARAM_CURRENT = "current";
    private static final String ANTD_TABLE_PARAM_PAGESIZE = "pageSize";
    private static final String ANTD_TABLE_PARAM_FILTER = "filter";
    private static final String ANTD_TABLE_PARAM_SORTER = "sorter";
    private static final String ANTD_TABLE_PARAM_ASC = "ascend";

    /**
     * 请求成功
     * @return
     */
    protected <T> R<T> success() {
        return R.ok(null);
    }

    /**
     * 请求成功
     *
     * @param data 数据内容
     * @param <T>  对象泛型
     * @return
     */
    protected <T> R<T> success(T data) {
        return R.ok(data);
    }

    /**
     * 请求失败
     *
     * @param msg 提示内容
     * @return
     */
    protected <T> R<T> failed(String msg) {
        return R.failed(msg);
    }

    /**
     * 请求失败
     *
     * @param errorCode 请求错误码
     * @return
     */
    protected <T> R<T> failed(IErrorCode errorCode) {
        return R.failed(errorCode);
    }

    /**
     * 解析分页参数,生成page对象
     *
     * @param request
     * @return
     */
    protected IPage<?> resolvePage(HttpServletRequest request) {
        String sCurrent = StrUtil.blankToDefault(request.getParameter(ANTD_TABLE_PARAM_CURRENT), "1");
        String pageSize = StrUtil.blankToDefault(request.getParameter(ANTD_TABLE_PARAM_PAGESIZE), "10");
        String filter = StrUtil.blankToDefault(request.getParameter(ANTD_TABLE_PARAM_FILTER), "{}");
        String sorter = StrUtil.blankToDefault(request.getParameter(ANTD_TABLE_PARAM_SORTER), "{}");

        long current = Long.parseLong(sCurrent);
        long size = Long.parseLong(pageSize);
        Page page = new Page(current, size);

        JSONObject jsonObject = JSONUtil.parseObj(sorter);
        if (!jsonObject.isEmpty()) {
            Set<String> keys = jsonObject.keySet();
            keys.forEach(key -> {
                String value = (String) jsonObject.get(key);
                boolean asc = ANTD_TABLE_PARAM_ASC.equalsIgnoreCase(value) ? true : false;
                key = StrUtil.toUnderlineCase(key);
                page.addOrder(new OrderItem(key, asc));
            });
        } else {
            OrderItem orderItem = defautltOrder();
            if (null != orderItem) page.addOrder(orderItem);
        }

        return page;
    }

    protected OrderItem defautltOrder() {
        return null;
    }

}
